// System includes
#include <QDebug>
#include <QPainterPath>
#include <stdlib.h>
#include <QMacStyle>
#include <QScrollBar>

// Local includes
#include "yignetworkchannelview.h"
#include "yig.h"
#include "graphics/yigsynthgraphic.h"
#include "graphics/yigcolorkit.h"
#include "gui/yiggraphicsscene.h"

extern QString USER_NAME;
extern bool ONLINE;

//const int NULL = 0;

YigNetworkChannelView::YigNetworkChannelView(QWidget *parent) :
    QGraphicsView(parent)
{

    QGLFormat glFormat( QGL::SampleBuffers );
    //glFormat.setSwapInterval( 1 ); // set VSync
    QGLWidget* viewportGL = new QGLWidget( glFormat );
    setViewportUpdateMode( QGraphicsView::FullViewportUpdate );
    setViewport(viewportGL);
    setRenderHints(QPainter::Antialiasing);
    setOptimizationFlag(QGraphicsView::DontAdjustForAntialiasing, true);
    YigGraphicsScene* yigScene = new YigGraphicsScene;
    yigScene->setSceneRect(0, 0, 1920, 1200);
    setScene(yigScene);

    scaleFactor = 1.0;
    selectionRect = new QGraphicsRectItem( QRect( 0, 0, 0, 0 ) );
    selectionRect->setPen( QColor( 0, 0, 0, 200 ) );
    selectionRect->setFlag(QGraphicsItem::ItemIgnoresTransformations);
    //selectionRect->setBrush( QColor( 69, 139, 19, 40 ) );
    QColor rectColor = YigColorKit::accent;
    rectColor.setAlpha(130);
    selectionRect->setBrush(rectColor);
    selectionRect->setZValue( 10000 );
    scene()->addItem( selectionRect );
    selectionRect->hide();

    //glWidget->startRendering();

    mActiveBool = false;
    setActiveView(mActiveBool);
    currentCableBool = false;
    mouseDownBool = false;
    cableCounter = 0;
    srand((unsigned) time(0));
    verticalScrollBar()->setStyle(new QMacStyle);
    horizontalScrollBar()->setStyle(new QMacStyle);

    QPalette scrollPalette = verticalScrollBar()->palette();
    scrollPalette.setColor(QPalette::Button, YigColorKit::focus2);
    verticalScrollBar()->setPalette(scrollPalette);

    scrollPalette = horizontalScrollBar()->palette();
    scrollPalette.setColor(QPalette::Button, YigColorKit::focus2);
    horizontalScrollBar()->setPalette(scrollPalette);
    setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
    setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn);

    /*
    QLinearGradient gradient(0, 0, 0, parent->geometry().height());
    gradient.setColorAt(0, YigColorKit::background2);
    gradient.setColorAt(0.005, QColor(255, 255, 255));
    gradient.setColorAt(1, QColor(190, 190, 190));
    gradient.setInterpolationMode(QGradient::ColorInterpolation);
    QBrush backgroundBrush(gradient);
    backgroundBrush.setStyle(Qt::LinearGradientPattern);*/
    //QBrush backgroundBrush(QPixmap(":/images/gui/YigAttractorBackground.png"));
    //scene()->setBackgroundBrush(YigColorKit::background);
    //backgroundPixmap = scene()->addPixmap(YigAttractor::renderAttractor(width(), height()));
    modCableParent = new QGraphicsLineItem();
    modCableParent->setZValue(-20);
    modCableParent->setFlag(QGraphicsItem::ItemHasNoContents, true);
    //modCableParent->setVisible(false);
    scene()->addItem(modCableParent);
    audioCableParent = new QGraphicsLineItem();
    audioCableParent->setZValue(-5);
    //audioCableParent->setVisible(false);
    audioCableParent->setFlag(QGraphicsItem::ItemHasNoContents, true);
    scene()->addItem(audioCableParent);
    /*
    QObject::connect(this, SIGNAL(synthForGLAdded(int,QPointF)),
                     glWidget->getGLThread(), SLOT(addSynth(int,QPointF)), Qt::QueuedConnection);
    QObject::connect(this, SIGNAL(synthForGLRemoved(int)), glWidget->getGLThread(), SLOT(removeSynth(int)), Qt::QueuedConnection);
    QObject::connect(this, SIGNAL(synthForGLMoved(int,QPointF)),
                     glWidget->getGLThread(), SLOT(setSynthPos(int,QPointF)), Qt::QueuedConnection);

    */

    //glWidget.lower();

    //setupViewport(&glWidget);

    //scene()->setBackgroundBrush(Qt::transparent);
    //setAttribute(Qt::WA_TranslucentBackground);
    //setWindowFlags(Qt::FramelessWindowHint | Qt::WindowSystemMenuHint);
    //QPalette p = viewport()->palette();
    //p.setColor(QPalette::Base, Qt::transparent);
    //viewport()->setPalette(p);
    //viewport()->setAutoFillBackground(false);
    //parent->setAttribute(Qt::WA_TranslucentBackground);
    //parent->setAutoFillBackground(false);
    //setStyleSheet("background-color: transparent;");
    //lower();
    //glWidget.raise();
    //glWidget.lower();
    //glWidget.setStyleSheet("background-color: transparent;");
    //glParent = new QWidget(parent);
    //glWidget.setParent(glParent);
    //glParent->lower();
    //glWidget.show();
    setActiveView(true);
    setMouseTracking(true);
    setFrameStyle(0);
    mouseCounter = 0;
    centerOn(0, 0);
    show();
}

YigNetworkChannelView::~YigNetworkChannelView()
{
    //glWidget->stopRendering();
    foreach(QString key, synthGraphicMap.keys())
    {
        delete synthGraphicMap[key];
    }
    synthGraphicMap.clear();

    foreach(QString key, cableGraphicMap.keys())
    {
        delete cableGraphicMap[key];
    }
    cableGraphicMap.clear();

    foreach(QString key, cursorGraphicMap.keys())
    {
        delete cursorGraphicMap[key];
    }
    cableGraphicMap.clear();

    delete selectionRect;
    delete audioCableParent;
    delete modCableParent;
}

void YigNetworkChannelView::dragMoveEvent(QDragMoveEvent *event)
{
    event->setDropAction(Qt::CopyAction);
    event->accept();
}

void YigNetworkChannelView::dropEvent(QDropEvent *event)
{
    event->setDropAction(Qt::CopyAction);
    event->accept();
    // Create point with offset so that the new ellipse centers on the mouse
    QPoint point(
                event->pos().x() - (YigSynthGraphic::ELLIPSE_SIZE/2),
                event->pos().y() - (YigSynthGraphic::ELLIPSE_SIZE/2)
    );

    QPointF pointF = mapToScene(point);

    float param1 = (float) rand() / (float) RAND_MAX;
    float param2 = (float) rand() / (float) RAND_MAX;

    emit dragAndDrop(USER_NAME, event->mimeData()->text(), pointF.toPoint(), param1, param2);
    //qDebug() << "Drag And Drop " << event->mimeData()->text();
}

void YigNetworkChannelView::setActiveView(bool activeBool)
{
    // Accept drag/drops for synth object creation
    setAcceptDrops(activeBool);
    // Interactivity for local user control
    setInteractive(activeBool);
    viewport()->setAcceptDrops(activeBool);
    mActiveBool = activeBool;
}

bool YigNetworkChannelView::getActiveBool()
{
    return mActiveBool;
}

void YigNetworkChannelView::clearSynths()
{

    foreach(QString key, synthGraphicMap.keys())
    {
        emit keyboardDeleteSynth(key);
    }
}

QList<YigSynthGraphic*> YigNetworkChannelView::getSynthGraphics()
{
    //lock.lockForRead();
    //QHashIterator<QString, YigSynthGraphic*> iter(synthGraphicMap);
    //lock.unlock();
    //QReadLocker locker(&lock);
    return synthGraphicMap.values();
}

QList<YigCableGraphic*> YigNetworkChannelView::getCableGraphics()
{
    return cableGraphicMap.values();
}

void YigNetworkChannelView::createSynthGraphic(YigSynth *yigSynth, QString key, QString synthName, QPoint point,
                                               float param1, float param2)
{
    if(!synthGraphicMap.contains(key))
    {
        YigSynthGraphic* synth = new YigSynthGraphic(synthName, key, point, param1, param2, yigSynth->getAudioOutBus(), scene());

        // Connect signals/slots
        QObject::connect(synth, SIGNAL(paramChanged(QString,YigSynthGraphic::ParamType,float)),
                         yigSynth, SLOT(setParam(QString,YigSynthGraphic::ParamType,float)));

        QObject::connect(synth, SIGNAL(paramChanged(QString,YigSynthGraphic::ParamType,float)),
                         this, SIGNAL(synthParamChanged(QString,YigSynthGraphic::ParamType,float)));

        QObject::connect(synth, SIGNAL(posChanged(QString,QPointF)), this, SIGNAL(synthPositionChanged(QString,QPointF)));

        QObject::connect(synth, SIGNAL(autoCableTriggered(QString,QString,YigCableGraphic::CableOutputType)),
                         this, SLOT(createCableGraphic(QString,QString,YigCableGraphic::CableOutputType)));

        QObject::connect(synth, SIGNAL(selectedChanged(QString,int)), this, SIGNAL(synthSelectedChanged(QString,int)));

        //scene()->addItem(synth);
        //synth->broadcastParams();
        synthGraphicMap.insert(key, synth);
        synth->autoCable();
        ((YigGraphicsScene*)scene())->addSynthBuffer(synth->getAudioOutBus());


        // OPENGL Thread connection/update
        //glWidget.getGLThread()->addSynthBuffer(synth->getAudioOutBus());
        //QObject::connect(synth, SIGNAL(posChanged(int,QPointF)), glWidget->getGLThread(), SLOT(setSynthPos(int,QPointF)));
        //emit synthForGLAdded(synth->getAudioOutBus(), synth->scenePos());
    }

}

void YigNetworkChannelView::destroySynthGraphic(QString key)
{
    /*
    if(currentCableBool)
    {
        removeCurrentCable();
    }*/

    YigSynthGraphic* synth = synthGraphicMap[key];
    ((YigGraphicsScene*)scene())->removeSynthBuffer(synth->getAudioOutBus());
    //glWidget.getGLThread()->removeSynthBuffer(synth->getAudioOutBus());
    //emit synthForGLRemoved(synth->getAudioOutBus());
    scene()->removeItem(synth);
    //deletedGraphics.append(synth);
    delete synth;
    synth = 0;
    synthGraphicMap.remove(key);
    selectedSynthKeys.removeAll(key);
    //emit keyboardDeleteSynth(key);
}

void YigNetworkChannelView::createCableGraphic(QString inputKey, QString outputKey, YigCableGraphic::CableOutputType outputType)
{

    if(outputType == YigCableGraphic::AUDIO)
    {
        QString mapKey = inputKey+outputKey+"AUDIO";
        if(!cableGraphicMap.contains(mapKey))
        {
            QPointF inputPoint(synthGraphicMap[inputKey]->pos());
            inputPoint.setX(inputPoint.x() + YigSynthGraphic::AUDIO_OUTPUT_X);
            inputPoint.setY(inputPoint.y() + YigSynthGraphic::AUDIO_OUTPUT_Y);

            QPointF outputPoint(synthGraphicMap[outputKey]->pos());
            outputPoint.setX(outputPoint.x() + YigSynthGraphic::AUDIO_INPUT_X);
            outputPoint.setY(outputPoint.y() + YigSynthGraphic::AUDIO_INPUT_Y);

            QLineF line(inputPoint, outputPoint);
            YigCableGraphic* cable = new YigCableGraphic(line, inputKey, outputKey, outputType,
                                                         synthGraphicMap[inputKey]->getAudioOutBus(), audioCableParent);
            //scene()->addItem(cable);
            cable->setOutputType(outputType);
            //cable->addArrow();
            addCable(mapKey, cable);
            synthGraphicMap[inputKey]->addAudioOutputCable(cable);
            synthGraphicMap[outputKey]->addAudioInputCable(cable);
        }
    }

    else if(outputType == YigCableGraphic::MODULATION)
    {
        QString mapKey = inputKey+outputKey+"MODULATION";
        if(!cableGraphicMap.contains(mapKey))
        {
            /*
            QPointF inputPoint(synthGraphicMap[inputKey]->pos());
            inputPoint.setX(inputPoint.x() + YigSynthGraphic::MOD_INPUT_X);
            inputPoint.setY(inputPoint.y() + YigSynthGraphic::MOD_INPUT_Y);

            QPointF outputPoint(synthGraphicMap[outputKey]->pos());
            outputPoint.setX(outputPoint.x() + YigSynthGraphic::MOD_INPUT_X);
            outputPoint.setY(outputPoint.y() + YigSynthGraphic::MOD_INPUT_Y);*/

            QPointF inputPoint(synthGraphicMap[inputKey]->pos());
            inputPoint.setX(inputPoint.x() + YigSynthGraphic::AUDIO_OUTPUT_X);
            inputPoint.setY(inputPoint.y() + YigSynthGraphic::AUDIO_OUTPUT_Y);

            QPointF outputPoint(synthGraphicMap[outputKey]->pos());
            outputPoint.setX(outputPoint.x() + YigSynthGraphic::AUDIO_INPUT_X);
            outputPoint.setY(outputPoint.y() + YigSynthGraphic::AUDIO_INPUT_Y);

            //currentCable->setPoint1(modPoint.toPoint());

            QLineF line(inputPoint, outputPoint);
            YigCableGraphic* cable = new YigCableGraphic(line, inputKey, outputKey, outputType,
                                                         synthGraphicMap[inputKey]->getAudioOutBus(), modCableParent);
            //scene()->addItem(cable);
            cable->setOutputType(outputType);
            cable->addArrow();
            addCable(mapKey, cable);
            synthGraphicMap[inputKey]->addAudioOutputCable(cable);
            synthGraphicMap[outputKey]->addModInputCable(cable);
            //qDebug() << "MODULATION CABLE";
        }
    }
}

void YigNetworkChannelView::destroyCableGraphic(QString mapKey)
{
    if(cableGraphicMap.contains(mapKey))
    {
        YigCableGraphic* cable = cableGraphicMap[mapKey];
        synthGraphicMap[cable->getInputKey()]->removeAudioOutputCable(mapKey);

        switch(cable->getOutputType())
        {
        case YigCableGraphic::AUDIO:
            synthGraphicMap[cable->getOutputKey()]->removeAudioInputCable(mapKey);
            break;

        case YigCableGraphic::MODULATION:
            synthGraphicMap[cable->getOutputKey()]->removeModInputCable(mapKey);
            break;

        case YigCableGraphic::NO_OUTPUT:
            //qDebug() << "NO CABLE REMOVED";
            break;
        }

        //cable->removeArrow();
        //scene()->removeItem(cable);
        //deletedGraphics.append(cable);
        delete cable;
        cable = 0;
        emit cableDestroyed(mapKey);
        cableGraphicMap.remove(mapKey);
    }
}

void YigNetworkChannelView::addUser(QString userName)
{
    if(userName != USER_NAME && (!cursorGraphicMap.contains(userName)))
    {
        YigCursor* cursorGraphic = new YigCursor(QString(userName+"Cursor"));
        cursorGraphicMap.insert(QString(userName+"Cursor"), cursorGraphic);
        cursorGraphic->setPos(scene()->sceneRect().bottomRight());
        scene()->addItem(cursorGraphic);
    }
}

void YigNetworkChannelView::removeUser(QString userName)
{
    scene()->removeItem(cursorGraphicMap.value(userName));
    delete cursorGraphicMap.value(userName);
    cursorGraphicMap.remove(userName);
}

void YigNetworkChannelView::updateCursorPositionX(QString userName, int xPos)
{
    if(userName != USER_NAME && cursorGraphicMap.contains(userName))
    {
        QPointF cursorPos = cursorGraphicMap.value(userName)->pos();
        cursorPos.setX(xPos);
        cursorGraphicMap.value(userName)->setPos(cursorPos);
    }
}

void YigNetworkChannelView::updateCursorPositionY(QString userName, int yPos)
{
    if(userName != USER_NAME && cursorGraphicMap.contains(userName))
    {
        QPointF cursorPos = cursorGraphicMap.value(userName)->pos();
        cursorPos.setY(yPos);
        cursorGraphicMap.value(userName)->setPos(cursorPos);
    }
}

void YigNetworkChannelView::updateSynthPositionX(QString mapKey, int xPos)
{
    if(synthGraphicMap.contains(mapKey))
    {
        YigSynthGraphic* synth = synthGraphicMap[mapKey];
        synth->setPos(QPoint(xPos, synth->pos().y()));
        //emit synthForGLMoved(synth->getAudioOutBus(), synth->scenePos());
    }

}

void YigNetworkChannelView::updateSynthPositionY(QString mapKey, int yPos)
{
    if(synthGraphicMap.contains(mapKey))
    {
        YigSynthGraphic* synth = synthGraphicMap[mapKey];
        synth->setPos(QPoint(synth->pos().x(), yPos));
        //emit synthForGLMoved(synth->getAudioOutBus(), synth->scenePos());
    }
}

void YigNetworkChannelView::updateSynthParam1(QString mapKey, float param1)
{
    if(synthGraphicMap.contains(mapKey))
    {
        synthGraphicMap[mapKey]->syncParam1(param1);
    }
}

void YigNetworkChannelView::updateSynthParam2(QString mapKey, float param2)
{
    if(synthGraphicMap.contains(mapKey))
    {
        synthGraphicMap[mapKey]->syncParam2(param2);
    }
}

void YigNetworkChannelView::updateSynthSelected(QString mapKey, QString userName)
{
    synthGraphicMap[mapKey]->setselectingUser(userName);
}

void YigNetworkChannelView::autoCableAllSynths()
{
    QHashIterator<QString, YigSynthGraphic*> i(synthGraphicMap);
    while(i.hasNext())
    {
        i.next();
        i.value()->autoCable();
    }
}

void YigNetworkChannelView::resizeEvent(QResizeEvent *event)
{
    //YigAttractor::init();
    //scene()->setBackgroundBrush(YigAttractor::renderAttractor(width(), height()));
    //glWidget->resize(event->size());
    //if( scene() )
    //    scene()->setSceneRect( 0, 0, event->size().width(), event->size().height());
    QGraphicsView::resizeEvent(event);
}

void YigNetworkChannelView::keyPressEvent(QKeyEvent *event)
{
    /*
      OLD DELETE CODE
    if( event->matches( QKeySequence::Cut ) || event->matches( QKeySequence::Delete ) )
    {
        while(scene()->selectedItems().size() > 0)
        {
            dynamic_cast<YigBaseGraphic*>(scene()->selectedItems().first())->keyboardDelete();
        }
    }*/

    if( event->matches( QKeySequence::Cut ) || event->matches( QKeySequence::Delete ) )
    {
        /*
        QList<QGraphicsItem*> items = scene()->selectedItems();
        for(int i = 0; i < items.size(); i++)
        {
            if(items.at(i)->type() == YigBaseGraphic::SynthGraphicType)
            {
                destroySynthGraphic(((YigSynthGraphic*) items.at(i))->getMapKey());
            }
        }*/

        if(ONLINE)
        {
            QList<QGraphicsItem*> selectedItems = scene()->selectedItems();
            QSet<QString> selectedKeys;
            for(int i = 0; i < selectedItems.size(); i++)
            {
                if(selectedItems.at(i)->type() == YigBaseGraphic::SynthGraphicType)
                {
                    selectedKeys.insert(((YigSynthGraphic*) selectedItems.at(i))->getMapKey());
                }

                else if(selectedItems.at(i)->type() == YigBaseGraphic::ModFieldType)
                {
                    selectedKeys.insert(((YigModField*) selectedItems.at(i))->getParentGraphic()->getMapKey());
                }

                else if(selectedItems.at(i)->type() == YigBaseGraphic::ModFieldType2)
                {
                    selectedKeys.insert(((YigModField2*) selectedItems.at(i))->getParentGraphic()->getMapKey());
                }
            }

            QSetIterator<QString> i(selectedKeys);
            while(i.hasNext())
            {
                emit keyboardDeleteSynth(i.next());
            }
        }

        else
        {
            while(scene()->selectedItems().size() > 0)
            {
                QGraphicsItem* item = scene()->selectedItems().takeFirst();
                if(item->type() == YigBaseGraphic::SynthGraphicType)
                {
                    //destroySynthGraphic(((YigSynthGraphic*) item)->getMapKey());
                    emit keyboardDeleteSynth(((YigSynthGraphic*) item)->getMapKey());
                }

                else if(item->type() == YigBaseGraphic::ModFieldType)
                {
                    //destroySynthGraphic(((YigModField*) item)->getParentGraphic()->getMapKey());
                    emit keyboardDeleteSynth(((YigModField*) item)->getParentGraphic()->getMapKey());
                }

                else if(item->type() == YigBaseGraphic::ModFieldType2)
                {
                    //destroySynthGraphic(((YigModField2*) item)->getParentGraphic()->getMapKey());
                    emit keyboardDeleteSynth(((YigModField2*) item)->getParentGraphic()->getMapKey());
                }
            }
        }
    }

    /*
    if(event->key() == Qt::Key_0)
    {
        qDebug() << "SAVE ATTRACTOR!";
        YigAttractor::init();
        qDebug() << YigAttractor::renderAttractor(width() * 16, height() * 16).save("YigAttractor.png", "PNG");
    }*/

    //makeSelectedSynthKeyList();
    //removeCurrentCable();
    //deletedGraphics.clear();

    // Always remember to call the parent's method
    QGraphicsView::keyPressEvent( event );
}


void YigNetworkChannelView::mouseMoveEvent(QMouseEvent *event)
{
    if(event->buttons().testFlag(Qt::LeftButton))
    {
        // handle selectionRect
        if( selectionRect->isVisible() )
        {
            //QPointF mouseDownView = mouseDownPos;
            lastMouseViewPos = mapToScene(event->pos()).toPoint();
            QRectF rubberRect( mouseDownPos, lastMouseViewPos );
            rubberRect = rubberRect.normalized();
            selectionRect->setRect( rubberRect );
            QPolygonF p = rubberRect;
            /*
            QPolygonF p;
            p.append(rubberRect.topLeft());
            p.append(rubberRect.topRight());
            p.append(rubberRect.bottomRight());
            p.append(rubberRect.bottomLeft()); */
            QPainterPath path;
            path.addPolygon( p );
            scene()->setSelectionArea( path, Qt::IntersectsItemShape );
        }
    }

    else if(event->buttons().testFlag(Qt::RightButton))
    {
        lastMouseViewPos = mapToScene(event->pos()).toPoint();
        QPoint scrollPoint = lastMouseViewPos - mouseDownPos;
        //int scrollX = horizontalScrollBar()->value() - scrollPoint.x();
        //int scrollY = verticalScrollBar()->value() - scrollPoint.y();
        //horizontalScrollBar()->setValue(scrollX);
        //verticalScrollBar()->setValue(scrollY);
        //scrollContentsBy(scrollX, scrollY);
        centerOn(mapToScene(viewport()->rect().center()) - scrollPoint);
    }

    if(ONLINE)
    {
        emit cursorPositionChanged(mapToScene(event->pos()).toPoint());
        /*
        if(mouseCounter >= 10)
        {
            emit cursorPositionChanged(event->pos());
            mouseCounter = 0;
        }

        else
        {
            mouseCounter++;
        }*/
    }
    QGraphicsView::mouseMoveEvent(event);
}


void YigNetworkChannelView::mousePressEvent(QMouseEvent *event)
{

    if( !scene()->itemAt( mapToScene( event->pos() ) ) )
    {
        if(event->buttons().testFlag(Qt::LeftButton))
        {
            mouseDownPos = mapToScene( event->pos() ).toPoint();
            lastMouseViewPos = mapToScene(event->pos()).toPoint();
            selectionRect->setRect( mouseDownPos.x(), mouseDownPos.y(), 0, 0 );
            //selectionRect->setRect( mapFromScene( mouseDownPos ).x(), mapFromScene( mouseDownPos ).y(), 0, 0 );
            selectionRect->show();
        }

        else if(event->button() == Qt::RightButton)
        {
            setCursor(Qt::ClosedHandCursor);
            mouseDownPos = mapToScene(event->pos()).toPoint();
        }

    }

    QGraphicsView::mousePressEvent(event);
}


void YigNetworkChannelView::mouseReleaseEvent(QMouseEvent *event)
{
    setCursor(Qt::ArrowCursor);
    if(selectionRect->isVisible())
    {
        QList<QGraphicsItem*> selectedItems = scene()->selectedItems();
        for(int i = 0; i < selectedItems.size(); i++)
        {
            if(selectedItems.at(i)->type() == YigBaseGraphic::ModFieldType)
            {
                ((YigModField*)selectedItems.at(i))->setSelected(true);
            }
        }
    }
    selectionRect->hide();

    QGraphicsView::mouseReleaseEvent(event);
}

void YigNetworkChannelView::wheelEvent(QWheelEvent *event)
{
    /*
    qreal factor = 1.2;
    if(event->delta() < 0)
    {
        factor = 1.0 / factor;
    }

    scaleFactor *= factor;

    scale(factor, factor);
    */

    int scroll;
    if(event->delta() < 0)
    {
        scroll = verticalScrollBar()->value() + 1;
    }

    else
    {
        scroll = verticalScrollBar()->value() -1;
    }

    //verticalScrollBar()->setValue(scroll);
    scrollContentsBy(0, scroll);

    QGraphicsView::wheelEvent(event);
}

void YigNetworkChannelView::addCable(QString mapKey, YigCableGraphic *cable)
{
    //QString cableMapKey = USER_NAME + cable->getInputKey() + cable->getOutputKey() + QString::number(cableCounter);
    //cableCounter++;
    //qDebug() << "NEW CABLE!: " << mapKey;
    cable->setSelectable(true);
    cable->setMapKey(mapKey);
    cable->setZValue(0);
    QObject::connect(cable, SIGNAL(cableKeyboardDeleted(QString)), this, SLOT(destroyCableGraphic(QString)));
    cableGraphicMap.insert(mapKey, cable);
    emit cableCreated(mapKey, cable->getInputKey(), cable->getOutputKey(), cable->getOutputType());
}
